<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { getProducts, Products, GetProductsParam, removeProduct } from '@/api/products'
import TableOption from '@/components/TableOption.vue'
import { EnumType } from '@/consts/public'
import ProductOption from './ProductOption.vue'

const token = localStorage.getItem('milk_mamage_token')
// excle 文件上传
const fileList = ref<UploadUserFile[]>([])
const onSuccess: UploadProps['onSuccess'] = (res) => {
  const { code } = res
  if (code === 200) {
    ElMessage.success('上传成功')
    getTableData({})
  } else {
    ElMessage.error('文件格式错误')
    console.log(res)
  }
}
const onError: UploadProps['onError'] = (res) => {
  ElMessage.error(res.message)
}
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('一次只能上传一个')
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
  return ElMessageBox.confirm(
    `确定清楚文件 ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

// 产品列表
const tableData = ref<Products[]>()
const getTableData = async (param: GetProductsParam) => {
  const data = await getProducts(param)
  tableData.value = data
}

const setProduct = (index: number, product: Products) => {
  showOptionDialog.value = true
  dialogType.value = 'set'
  defaultRuleForm.value = product
}

const deleteProduct = async (index: number, product: Products) => {
  try {
    await ElMessageBox.confirm(
      '确定删除当前产品？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }
  try {
    await removeProduct(product.id)
    await getTableData({})
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}
// 搜索
const optionsList: EnumType[] = [
  {
    label: '简码',
    value: 'coding'
  },
  {
    label: '品名',
    value: 'name'
  }
]
const search = (prarm: object) => {
  getTableData(prarm)
}

// 操作产品信息
const showOptionDialog = ref(false)
const dialogType = ref('add')
const defaultRuleForm = ref<Products>({} as Products)

const defaultButtonoption = () => {
  showOptionDialog.value = true
  dialogType.value = 'add'
  defaultRuleForm.value = {} as Products
}

// 生命周期
onMounted(async () => {
  await getTableData({})
})

</script>
<template>
  <el-card shadow="Never">
    <el-upload
      class="upload-demo"
      :headers="{ Authorization: `${token}`}"
      action="http://127.0.0.1:6066/admin/upload"
      :before-remove="beforeRemove"
      :on-success="onSuccess"
      :on-error="onError"
      multiple
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
      accept=".xls, .xlsx, .xlsm, .xlsb"
    >
      <el-button type="primary">上传 excle 表格</el-button>
    </el-upload>
  </el-card>
  <el-card shadow="Never" class="product-table-card">
    <TableOption
      :optionsList=optionsList
      defaultButtonText="新增产品"
      @search="search"
      @defaultButtonoption="defaultButtonoption"
    />
    <el-table :data="tableData" height="500" stripe style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="coding" label="简码" width="120" />
      <el-table-column prop="name" label="品名"/>
      <el-table-column prop="purchasing_price" label="进价" width="100"/>
      <el-table-column prop="selling_price" label="售价" width="100"/>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button type="text" size="small" @click="setProduct(scope.$index, scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteProduct(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <ProductOption
    :showAddDialog="showOptionDialog"
    :dialogType="dialogType"
    :defaultRuleForm="defaultRuleForm"
    @closeDialog="showOptionDialog = false"
    @optionSuccess="getTableData({}), showOptionDialog = false"
  />
</template>

<style lang="scss" scoped>
  .product-table-card {
    margin-top: 10px;
  }
</style>
